/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.msg.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.utils.JPushUtil;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.mapper.MemberMapper;
import com.jeeplus.modules.msg.entity.Msg;
import com.jeeplus.modules.msg.mapper.MsgMapper;

/**
 * 用户消息Service
 * @author lixinapp
 * @version 2019-10-16
 */
@Service
@Transactional(readOnly = true)
public class MsgService extends CrudService<MsgMapper, Msg> {
	@Autowired
	private MemberMapper memberMapper;
	
	public Msg get(String id) {
		return super.get(id);
	}
	
	public List<Msg> findList(Msg msg) {
		return super.findList(msg);
	}
	
	public Page<Msg> findPage(Page<Msg> page, Msg msg) {
		return super.findPage(page, msg);
	}
	
	@Transactional(readOnly = false)
	public void save(Msg msg) {
		super.save(msg);
	}
	
	@Transactional(readOnly = false)
	public void delete(Msg msg) {
		super.delete(msg);
	}
	
	/**
	 * 添加消息
	 */
	@Transactional(readOnly = false)
	public void insert(Member member, String title, String content) {
		Msg msg = new Msg();
		msg.setMember(member);
		msg.setTitle(title);
		msg.setContent(content);
		msg.setState("0");
		msg.setType("0");
		super.save(msg);
		
		// 异步推送
		Member m = memberMapper.get(member);
		if (m != null && StringUtils.isNotBlank(m.getToken())) {
			new Thread(new Runnable() {
				public void run() {
					try {
						JPushUtil.registerTitle(title, content, m.getToken());
					} catch (Exception e) {
						logger.error("极光推送失败：" + e.getMessage());
					}
				}
			}).start();
		}
	}
}